package com.yt.fras.controller;

import com.alibaba.fastjson.JSON;
import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.yt.fras.pojo.base.JsonResult;
import com.yt.fras.service.MailService;
import com.yt.fras.service.UserService;
import com.yt.fras.utils.MathRandom;
import com.yt.fras.utils.RedisUtil;
import com.yt.fras.utils.ResultTool;
import com.yt.fras.utils.SetContent;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;

/**
 * ClassName:CaptchaController
 * Package:com.yt.fras.controller
 * Description:
 * 验证码模块
 *
 * @date:2021/10/27 22:15
 * @author:yt
 */

@RestController
@RequestMapping("/fras/captcha")
@Api(tags = "验证码模块")
public class CaptchaController {

    @Autowired
    @Qualifier("captchaProducer")
    private DefaultKaptcha captchaProducer;

    @Autowired
    private UserService userService;

    @Autowired
    private MailService mailService;

    @Autowired
    private RedisUtil redisUtil;

    private String capText;

    /**
     * 获取图片验证码
     *
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @PostMapping("/codeImage")
    @ApiOperation(value = "获取图片验证码")
    @ApiResponses({
            @ApiResponse(code = 500, message = "系统出现错误~")
    })
    public String getCaptchaImage(HttpServletRequest request, HttpServletResponse response) throws Exception {
        HttpSession session = request.getSession();
        // 清除浏览器的缓存
        response.setDateHeader("Expires", 0);
        // Set standard HTTP/1.1 no-cache headers.
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        // Set IE extended HTTP/1.1 no-cache headers (use addHeader).
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        // Set standard HTTP/1.0 no-cache header.
        response.setHeader("Pragma", "no-cache");
        // return a jpeg
        response.setContentType("image/jpeg");
        // 浏览器记忆功能-----当前过浏览器和服务器交互成功以后下载的图片和资源会进行缓存一次。下次刷新的时候就不会在到服务器去下载。
        // 获取KAPTCHA验证的随机文本
        capText = captchaProducer.createText();
        // 将生成好的图片放入会话中
        session.setAttribute(Constants.KAPTCHA_SESSION_KEY, capText);
        // create the image with the text
        BufferedImage bi = captchaProducer.createImage(capText);
        ServletOutputStream out = response.getOutputStream();
        // write the data out
        ImageIO.write(bi, "jpg", out);
        try {
            out.flush();
        } finally {
            out.close();//关闭
        }
        return JSON.toJSONString(ResultTool.success());
    }

    /**
     * 获取图片验证码中的验证码
     *
     * @return
     */
    @GetMapping("/code")
    @ApiOperation(value = "获取图片验证码中的验证码")
    @ApiResponses({
            @ApiResponse(code = 200, message = "获取成功！"),
            @ApiResponse(code = 500, message = "系统出现错误~")
    })
    public String getCaptchaCode() {
        JsonResult result = ResultTool.success(capText);
        result.setMsg("获取成功！");
        return JSON.toJSONString(result);
    }

    /**
     * 获取邮箱验证码
     *
     * @param username
     * @param email
     * @return
     */
    @PostMapping("/email/{username}/{email}")
    @ApiOperation(value = "获取邮箱验证码")
    @ApiResponses({
            @ApiResponse(code = 200, message = "获取成功！"),
            @ApiResponse(code = 500, message = "系统出现错误~")
    })
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "path", name = "username", value = "用户名", required = true),
            @ApiImplicitParam(paramType = "path", name = "email", value = "邮箱", required = true)
    })
    public String getEmailCode(@PathVariable String username, @PathVariable String email) {
        JsonResult result;
        if (userService.verificationEmail(username, email)) {
            int emailCode = MathRandom.mathRandom1(6);
            mailService.sendHtmlMail(email, "重置密码", SetContent.code(username, String.valueOf(emailCode)));
            redisUtil.hSet(username, "emailCode", emailCode,30*60);
            result =ResultTool.success();
            result.setMsg("获取成功！");
        } else {
            result = ResultTool.fail();
            result.setMsg("该邮箱不属于该账号！请重新输入！");
        }
        return JSON.toJSONString(result);
    }

    /**
     * 验证用户名是否重复
     *
     * @param username
     * @return
     */
    @PostMapping("/verifyUsername/{username}")
    @ApiOperation(value = "验证用户名是否重复")
    @ApiResponses({
            @ApiResponse(code = 200, message = "该用户名可使用！"),
            @ApiResponse(code = 0, message = "该用户名已存在！"),
            @ApiResponse(code = 500, message = "系统出现错误~")
    })
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "path", name = "username", value = "用户名", required = true),
    })
    public String verifyUsername(@PathVariable String username) {
        JsonResult result;
        if (userService.verificationUsername(username)) {
            result = ResultTool.success();
            result.setMsg("该用户名可使用！");
        } else {
            result = ResultTool.fail();
            result.setMsg("该用户名已存在！");
        }
        return JSON.toJSONString(result);
    }

    /**
     * 验证邮箱是否属于用户
     *
     * @param username
     * @param email
     * @return
     */
    @PostMapping("/verifyEmail/{username}/{email}")
    @ApiOperation(value = "验证邮箱是否属于用户")
    @ApiResponses({
            @ApiResponse(code = 200, message = "邮箱正确！"),
            @ApiResponse(code = 0, message = "该邮箱不属于该账号！请重新输入！"),
            @ApiResponse(code = 500, message = "系统出现错误~")
    })
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "path", name = "username", value = "用户名", required = true),
            @ApiImplicitParam(paramType = "path", name = "email", value = "邮箱", required = true)
    })
    public String verifyEmail(@PathVariable String username, @PathVariable String email) {
        JsonResult result;
        if (userService.verificationEmail(username, email)) {
            result = ResultTool.success();
            result.setMsg("邮箱正确！");
        } else {
            result = ResultTool.fail();
            result.setMsg("该邮箱不属于该账号！请重新输入！");
        }
        return JSON.toJSONString(result);
    }

}
